package org.jeecg.modules.wechatSendMessage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.config.StaticConfig;
import org.jeecg.modules.sggg.entity.SgMember;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "发送微信订阅消息")
@RestController
@Slf4j
public class subscribeMessage {



    /**
     * 获取订阅消息接口所需的token
     *
     * @return
     */
    public static String getAccessToken() {
        StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class);
        String appID = staticConfig.getAppID(); //小程序的appid
        String appSecret = staticConfig.getAppSecret(); //小程序的秘钥
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", appID);
        params.put("APPSECRET", appSecret);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        return object.getString("access_token");
    }

    /**
     * 发送微信订阅消息
     *
     * @param wxMssVo 服务通知参数实体类
     *        touser (String) 用户的openId
     *        template_id (String) 订阅消息模板Id
     *        page (String) 点击消息跳转小程序的页面（默认首页）
     *        data (Map<String, TemplateData>) 推送的文字变量
     *
     *  wxMssVo.data 示例代码：
     *  Map<String, TemplateData> m = new HashMap<>(4);
     *  m.put("thing1", new TemplateData(参数值));
     *  m.put("thing2", new TemplateData(参数值));
     *  m.put("time3", new TemplateData(参数值));
     *  wxMssVo.setData(m);
     */
    public void send(WxMssVo wxMssVo) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class);
        log.info("发送微信订阅消息回调：" + responseEntity);
    }
}
